<?php

namespace App\Livewire;

use App\Models\Category;
use App\Models\Video;
use Illuminate\Support\Collection;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

class CategoryShow extends Component
{
    use WithPagination;

    public int $perPage = 4;

    public int $page = 1;

    public Collection $collection;

    public bool $hasMorePages;

    public Category $category;

    #[Url]
    public string $sortBy = '';

    public function mount(): void
    {
        $this->collection = Collection::make();

        $this->loadMore();
    }

    public function loadMore(): void
    {
        $collection = Video::query()
            ->whereRelation('categories', 'id', $this->category->getKey())
            ->latest($this->getSortBy())
            ->simplePaginate(perPage: 10, page: $this->page);

        $this->collection->push(...$collection->items());

        if ($this->hasMorePages = $collection->hasMorePages()) {
            $this->page++;
        }
    }

    protected function getSortBy(): ?string
    {
        return match ($this->sortBy) {
            'hot' => 'visits',
            default => null
        };
    }

    public function render()
    {
        return view('livewire.category-show');
    }
}
